package com.yanfei.zero.infrastructure.workflow;

import java.util.HashMap;
import java.util.Map;

import org.camunda.bpm.client.spring.annotation.ExternalTaskSubscription;
import org.camunda.bpm.client.task.ExternalTask;
import org.camunda.bpm.client.task.ExternalTaskHandler;
import org.camunda.bpm.client.task.ExternalTaskService;
import org.springframework.stereotype.Component;

import com.yanfei.zero.domain.order.repository.OrderRepository;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
@Component
@ExternalTaskSubscription("pickUp") // create a subscription for this topic name
@Slf4j
public class CamundaPickUpOrderHandler implements ExternalTaskHandler {
	  @Resource
	  private OrderRepository orderRepository;
	  
	  @Override
	  public void execute(ExternalTask externalTask, ExternalTaskService externalTaskService) {

	    // only for the sake of this demonstration, we generate random data
	    // in a real-world scenario, we would load the data from a database
	    String orderNumber = externalTask.getVariable("orderNumber");
	    try {
	    	 // complete the external task
	    	  int a = 2/0;
	    	  externalTaskService.complete(externalTask);
		} catch (Exception e) {
			// TODO: handle exception
			
	        // 如果发生异常，报告任务失败  
	        // 可以选择是否携带错误详情（取决于你的业务需求和Camunda版本）  
	        Map<String, Object> errorDetails = new HashMap<>();  
	        errorDetails.put("errorMessage", "事务异常测试");  
	        errorDetails.put("errorCode", 5);  
	        // ... 可以添加更多错误详情  
	        log.info("pickUp report error event");   
	        externalTaskService.handleFailure(externalTask.getId(),"address error found", "address error found", 2, 10000);  
	        // handleFailure方法的参数依次是：  
	        // 任务ID, 错误消息, 错误详情, 重试次数, 重试间隔（毫秒） 
			
		}

	    log.info("pickUp orderNumber{}!", new Object[]{orderNumber});
	  }

	}
